package com.example.eda.event;

import org.springframework.amqp.AmqpException;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional
public class TransactionPublisher {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    public void sendTransactionalMessage(String message) {
        rabbitTemplate.execute(channel -> { // 这里接收的是Channel对象
            try {
                channel.txSelect(); // 开启事务
                rabbitTemplate.convertAndSend("tx_fanout_exchange", "", message);
                channel.txCommit(); // 提交事务
                return null;
            } catch (Exception e) {
                channel.txRollback(); // 回滚事务
                throw new AmqpException("Message send failed", e);
            }
        });
    }

}
